<template>
  <div class="app-container dict-customFieldSetList-list-wrap">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="字段大类">
        <el-select v-model="queryParams.type" placeholder="请选择" clearable @change="changeType">
          <el-option v-for="dict in dict.type.field_category" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="字段集">
        <el-select v-model="queryParams.setId" placeholder="请选择" clearable>
          <el-option v-for="item in ziduanji" :key="item.id" :label="item.label" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择" clearable>
          <el-option v-for="dict in dict.type.custom_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>

      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="clickAddbtn"
          v-hasPermi="['custom:customField:add']">添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" :disabled="multiple" size="mini" @click="handleDelete"
          v-hasPermi="['custom:customField:del']">删除</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" max-height="550" :data="dataList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handelEdit(scope.row)" v-hasPermi="['custom:customField:edit']">
            编辑</el-button>
          <!-- <el-button size="mini" type="text" >禁用</el-button>   -->
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="label"></el-table-column>
      <el-table-column label="ID" prop="field" />
      <el-table-column label="数据类型" prop="dataType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.custom_field_type" :value="scope.row.dataType" />
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="state">
        <!-- <template slot-scope="scope">
          <dict-tag :options="dict.type.custom_state" :value="scope.row.state"/>
        </template> -->
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state" active-value="NORMAL" inactive-value="DEACTIVATED"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <el-dialog :title="ruleForm.id?'编辑自定义字段集':'添加自定义字段集'" :visible.sync="dialogVisible" width="600px">
      <div class="dialog-form-box">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
          <el-form-item label="字段大类" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择" clearable @change="changeType" style="width: 85%;"
              :disabled="ruleForm.id?true:false">
              <el-option v-for="dict in dict.type.field_category" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="字段集" prop="setId">
            <el-select v-model="ruleForm.setId" placeholder="请选择" clearable style="width: 85%;">
              <el-option v-for="item in ziduanji" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="标签值：" prop="label">
            <el-input v-model="ruleForm.label" style="width: 85%;"></el-input>
          </el-form-item>
          <el-form-item label="ID：" prop="field">
            <el-input v-model="ruleForm.field" style="width: 85%;"></el-input>
          </el-form-item>
          <el-form-item label="类型：" prop="dataType">
            <el-select v-model="ruleForm.dataType" placeholder="请选择" :disabled="ruleForm.id?true:false" clearable
              style="width: 85%;">
              <el-option v-for="dict in dict.type.custom_field_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否必填：" prop="isRequired">
            <el-select v-model="ruleForm.isRequired" placeholder="请选择" clearable style="width: 85%;">
              <el-option v-for="dict in dict.type.is_required" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="下拉值：" prop="entityId" v-if="ruleForm.dataType=='SELECTION'">
            <el-select v-model="ruleForm.entityId" placeholder="请选择" clearable style="width: 85%;"
              @change="changeLevel">
              <el-option v-for="item in xialaList" :key="item.dictType" :label="item.dictName" :value="item.dictType" />
            </el-select>
          </el-form-item>
          <el-form-item label="等级：" prop="level" v-if="ruleForm.dataType=='SELECTION'">
            <el-select v-model="ruleForm.level" placeholder="请选择" clearable style="width: 85%;">
              <el-option v-for="item in levelList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="使用范围：" prop="fanwei" v-if="usedFanwei && usedFanwei.length>0">
            <el-checkbox-group v-model="ruleForm.fanwei">
              <el-checkbox v-for="item in usedFanwei" :key="item.fieldId" :label="item.fieldId">{{item.fieldName}}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handelConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    customFieldList,
    customFieldAdd,
    customFieldEdit,
    customFieldBatch,
    customFieldSetListsType,
    getDataList,
    selectCustom,
    getLevel,
    customFieldGet,
    customFieldEditState
  } from '@/api/system/dict/customerField.js'

  export default {
    name: "DictCustomFieldSetList",
    dicts: ['field_category', 'field_type', 'data_type', 'custom_state', 'custom_field_type', 'is_required'],
    data() {
      return {
        loading: false,
        multiple: true,
        queryParams: {
          type: '',
          setId: '',
          state: '',
          pageNum: 1,
          pageSize: 30
        },
        dialogVisible: false,
        ruleForm: {
          fanwei: []
        },
        rules: {
          type: [{
            required: true,
            message: "请选择",
            trigger: "change"
          }],
          setId: [{
            required: true,
            message: "请选择",
            trigger: "change"
          }],
          label: [{
            required: true,
            message: "请输入标签值",
            trigger: "change"
          }],
          field: [{
            required: true,
            message: "请选择",
            trigger: "change"
          }],
          dataType: [{
            required: true,
            message: "请选择",
            trigger: "change"
          }],
        },
        companyData: [],
        dataList: [{
          name: '123',
          id: '1'
        }],
        total: 0,
        usedFanwei: [],
        ziduanji: [],
        xialaList: [],
        levelList: []


      };
    },


    created() {
      this.getList()
      this.selectCustom()
    },
    mounted() {

    },
    methods: {
      changeType(val) {
        this.queryParams.setId = ''
        this.ruleForm.setId = ''
        this.getcustomFieldSetListsType(val)
        this.shiyongfanwei(val)
      },
      //查询字段集
      getcustomFieldSetListsType(type) {
        customFieldSetListsType({
          type: type
        }).then(res => {
          this.ziduanji = res.data
        })
      },
      //查询使用范围
      shiyongfanwei(type) {
        getDataList({
          type: type
        }).then(res => {
          this.usedFanwei = res.data
        })
      },
      //查询下拉值
      selectCustom() {
        selectCustom().then(res => {
          this.xialaList = res.data
        })
      },
      changeLevel(val) {
        this.ruleForm.level = ''
        this.getLevelList(val)
      },
      //获取level等级
      getLevelList(type) {
        getLevel({
          type: type
        }).then(res => {
          let levelList = []
          for (let i = 1; i <= Number(res.data); i++) {
            levelList.push(i)
          }
          console.log(res.data, levelList)
          this.levelList = levelList
        })
      },
      getList() {
        this.loading = true;
        customFieldList(this.queryParams).then(res => {
          this.dataList = res.rows
          this.total = res.total
          this.loading = false;
        })
      },
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      resetQuery() {
        this.resetForm("queryForm");
        this.queryParams = {
          type: '',
          setId: '',
          state: '',
          pageNum: 1,
          pageSize: 30

        }
        this.handleQuery();
      },
      // 用户状态修改
      handleStatusChange(row) {
        let text = row.state == "NORMAL" ? "启用" : "停用";
        this.$modal.confirm('确认要 ' + text + ' “' + row.field + '” 吗？').then(() => {
          customFieldEditState({
            id: row.id,
            state: row.state
          }).then(res => {
            this.getList()
            this.$modal.msgSuccess(text + "成功");
          })
        }).catch(() => {
          row.state = row.status == "NORMAL" ? "DEACTIVATED" : "NORMAL";
        });
      },
      handleSelectionChange(selection) {
        this.seletIds = selection.map(item => item.id)
        this.multiple = !selection.length
      },
      // 表单重置
      reset() {
        this.resetForm("ruleForm");
        this.ruleForm = {
          id: '',
          type: '',
          setId: '',
          label: '',
          field: '',
          dataType: '',
          isRequired: '',
          entityId: '',
          level: '',
          fanwei: []
        };
        this.usedFanwei = []
        this.levelList = []
      },
      //批量删除产品
      handleDelete() {
        let that = this
        let ids = ''
        this.seletIds.forEach((item, i) => {
          if (this.seletIds.length - 1 == i) {
            ids += item
          } else {
            ids += item + ','
          }
        });
        this.$modal.confirm('是否确认删除选中的数据项？').then(function () {
          customFieldBatch({
            ids: ids
          }).then(res => {
            that.getList();
            that.$modal.msgSuccess("删除成功");
          });
        }).catch(function () {});
      },
      //点击添加按钮弹出表单
      clickAddbtn() {
        this.dialogVisible = true
        this.reset()
      },
      //点击编辑弹出编辑表单并赋值
      handelEdit(row) {
        this.reset()
        this.customFieldGet(row.id)
      },
      //详情查询
      customFieldGet(id) {
        customFieldGet({
          id: id
        }).then(res => {
          this.dialogVisible = true
          this.ruleForm.id = res.data.id
          this.ruleForm.type = res.data.type
          this.getcustomFieldSetListsType(res.data.type) //字段及查询
          this.shiyongfanwei(res.data.type) //使用范围查询
          this.ruleForm.setId = res.data.setId
          this.ruleForm.label = res.data.label
          this.ruleForm.field = res.data.field
          this.ruleForm.dataType = res.data.dataType
          this.ruleForm.isRequired = res.data.isRequired.toString()
          this.ruleForm.entityId = res.data.entityId
          this.getLevelList(res.data.entityId)
          this.ruleForm.level = res.data.level
          let arr = []
          res.data.customFieldLinks.forEach(item => {
            arr.push(item.entityId)
          })
          this.ruleForm.fanwei = arr
        })
      },
      //点击提交表单
      handelConfirm() {
        let customFieldLinks = [] //id,fieldId,entityId
        this.ruleForm.fanwei.forEach(item => {
          customFieldLinks.push({
            entityId: item
          })
        })
        this.$refs["ruleForm"].validate(valid => {
          if (valid) {
            const params = {
              id: this.ruleForm.id || null,
              type: this.ruleForm.type,
              setId: this.ruleForm.setId,
              label: this.ruleForm.label,
              field: this.ruleForm.field,
              dataType: this.ruleForm.dataType,
              isRequired: this.ruleForm.isRequired,
              entityId: this.ruleForm.entityId,
              level: this.ruleForm.level,
              customFieldLinks: customFieldLinks
            }
            if (this.ruleForm.id) {
              customFieldEdit(params).then(res => {
                this.$modal.msgSuccess("修改成功");
                this.dialogVisible = false;
                this.getList();
              })
            } else {
              customFieldAdd(params).then(res => {
                this.$modal.msgSuccess("添加成功");
                this.dialogVisible = false;
                this.getList();
              })
            }
          }
        })
      }
    }
  };

</script>

<style rel="stylesheet/scss" lang="scss">

</style>
